// server.js
import { createServer } from 'http'
import { Server } from 'socket.io'

// 创建 HTTP 服务器
const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  res.end('WebSocket Server is running\n')
})

// 创建 Socket.io 实例
const io = new Server(server, {
  cors: {
    origin: '*', // 允许所有客户端连接（生产环境中应限制为特定域名）
    methods: ['GET', 'POST']
  }
})

// 监听客户端连接
io.on('connection', (socket) => {
  console.log('A client connected:', socket.id)

  // 监听客户端发送的消息
  socket.on('sendMessage', (message) => {
    console.log('Received message:', message)

    // 广播消息给所有客户端
    io.emit('messageReceived', message)
  })

  // 监听客户端断开连接
  socket.on('disconnect', () => {
    console.log('A client disconnected:', socket.id)
  })
})

// 启动服务器
const PORT = 3000
server.listen(PORT, () => {
  console.log(`WebSocket server is running on http://localhost:${PORT}`)
})
